<?php

namespace app\product\logic;

use app\common\library\Excel;
use app\common\library\RedissLock;
use app\common\service\CommonSystemImportService;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use app\api\logic\UploadTestLogic;
use app\product\logic\InventoryLogic;

class ProductInventoryLogic extends BasicLogic
{


    /**
     * @desc   获取产品库存列表
     * @author luckyXiong
     * @date   2024-07-21
     */
    public function getList($params=[]){
        $limit                   = getIsset($params,'limit',10);
        $spu                     = getIsset($params,'spu');
        $create_time             = getIsset($params,'create_time');
        $inventory_quantity_new  = getIsset($params,'inventory_quantity_new');
        $on_way_quantity         = getIsset($params,'on_way_quantity');
        $not_send_quantity       = getIsset($params,'not_send_quantity');
        $all_inventory_quantity  = getIsset($params,'all_inventory_quantity');
        $lack_inventory_quantity = getIsset($params,'lack_inventory_quantity');

        $where = [];
        $order = [];
        if($spu){
            $where[] = ['spu', '=', $spu];
        }

        if ($create_time) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }


        if($inventory_quantity_new){
             $order['inventory_quantity_new'] = $inventory_quantity_new;
        }

        if($on_way_quantity){
            $order['on_way_quantity'] = $on_way_quantity;
        }

        if($not_send_quantity){
            $order['not_send_quantity'] = $not_send_quantity;
        }

        if($all_inventory_quantity){
            $order['all_inventory_quantity'] = $all_inventory_quantity;
        }

        if($lack_inventory_quantity){
            $order['lack_inventory_quantity'] = $lack_inventory_quantity;
        }

        if(!$inventory_quantity_new && !$on_way_quantity && !$not_send_quantity && !$all_inventory_quantity && !$lack_inventory_quantity){
            $order['not_send_quantity']       = 'desc';
        }


        $res   = Db::name('product_inventory')
            ->field('id,spu,product_name,sum(inventory_quantity) as inventory_quantity,sum(on_way_quantity) as on_way_quantity,sum(not_send_quantity) as not_send_quantity,
            sum(all_inventory_quantity) as all_inventory_quantity,sum(inventory_quantity_new) as inventory_quantity_new,
            warehouse,warehouse,remark,create_time,update_time,product_images,sum(lack_inventory_quantity) as lack_inventory_quantity')
            ->where($where)
            ->group('spu')
            ->order($order)
            ->paginate($limit);
        $list = $res->items()?:[];

        $spus = array_column($list,'spu');
        //批量获取图片地址;
        $track_number = Db::name('product_spu_inventory')->field('id,spu,track_number')->whereIn('spu',$spus)->select()->toArray();
        $track_number_map =  array_column($track_number,'track_number','spu');

        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');
        foreach($list as $k=>$v){
            $purchase_info  = self::get_purchase_info($v['spu']);
            $product_images = $products_map[$v['spu']]??[];
            $list[$k]['product_images']         = $product_images['product_images']??'';
            $list[$k]['purchase_time']          = $purchase_info['purchase_time']??'';
            $list[$k]['purchase_number_num']    = 0;
            $list[$k]['track_number']    = $track_number_map[$v['spu']]??'';
            $product_images_product       = $products_map[$v['spu']]??[];
            $product_images               = $product_images_product['product_images']??[];
            $display_images               = $product_images ? current(json_decode($product_images)) : '';
            $list[$k]['product_images']   = $display_images;
        }
        //获取三个库存的总计
        $total_info = Db::name('product_inventory')->where($where)
                     ->field('id,on_way_quantity,inventory_quantity_new,all_inventory_quantity,not_send_quantity')
                     ->select()->toArray();
        $total_inventory_quantity     = array_sum(array_column($total_info, 'inventory_quantity_new'));
        $total_on_way_quantity        = array_sum(array_column($total_info, 'on_way_quantity'));
        $total_not_send_quantity      = array_sum(array_column($total_info, 'not_send_quantity'));
        $total_all_inventory_quantity = array_sum(array_column($total_info, 'all_inventory_quantity'));

        $data = [
            'list'                         => $list,
            'total'                        => $res->total(),
            'total_inventory_quantity'     => $total_inventory_quantity>0 ? $total_inventory_quantity :0,
            'total_on_way_quantity'        => $total_on_way_quantity,
            'total_not_send_quantity'      => $total_not_send_quantity,
            'total_all_inventory_quantity' => $total_all_inventory_quantity,
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }

    /**
     * @desc   数据排序更新生产方法
     * @author luckyXiong
     * @date   2024-08-02
     */
    public function get_purchase_info($spu){
        $total_info = Db::name('product_buy_inventory')->where('spu',$spu)
                       ->field('id,purchase_number,purchase_time')
                       ->group('purchase_number')
                       ->select();
        $total_info = objectToArray($total_info);
        $purchase_time   = '';

        if($total_info){
              $purchase_time   = array_column($total_info,'purchase_time');
              $purchase_time   = implode(',',$purchase_time);
        }

        return [
            'purchase_time'        =>$purchase_time,
        ];
    }


    /**
     * @desc   数据排序更新生产方法
     * @author luckyXiong
     * @date   2024-08-02
     */
    public function removeInventory(){
        //update 2024-08-14  同时清空qu_product_inventory中数据，获取最新的;
        Db::execute('TRUNCATE TABLE qu_product_inventory');
    }

    /**
     * @desc   数据排序更新消费方法
     * @author luckyXiong
     * @date   2024-08-02
     */
    public function updateSpuConsumer($info){
        //统计spu信息;
        $spu = $info['spu']??'';
        //供应商;
        $supply_info = self::supply_info(['spu'=>$spu]);
        $supply_id   = $supply_info['id'] ?? 0;
        $supply_name = $supply_info['supply_name'] ?? "";

        $field    = 'id,spu,sum(sku_1days) as sku_1days';
        $all_list = Db::name('purchase_suggest_plan')->field($field)
            ->where('spu',$spu)
            ->select()
            ->toArray();
        $spu_info = $all_list[0]??"";
        $sku_1days = $spu_info['sku_1days']??0;
        $field2    = 'spu,sum(all_inventory_quantity) as all_inventory_quantity,sum(on_way_quantity) as on_way_quantity,sum(not_send_quantity) as not_send_quantity';
        $all_inventory_list = Db::name('product_inventory')->field($field2)
            ->where('spu',$spu)
            ->group('spu')
            ->find();
        $arr  = [
            'spu'                     =>$spu,
            'supply_id'               =>$supply_id,
            'supply_name'             =>$supply_name,
            'all_inventory_quantity'  =>$all_inventory_list['all_inventory_quantity']??0,
            'on_way_quantity'         =>$all_inventory_list['on_way_quantity']??0,
            'not_send_quantity'       =>$all_inventory_list['not_send_quantity']??0,
            'sku_1days'               =>ceil($sku_1days),
            'create_time'             =>date("Y-m-d H:i:s", time()),
        ];
        Db::name('purchase_suggest_plan_spu')->insert($arr);
        return  true;
    }



    /**
     * @desc    供应商
     * @date    2024/7/16
     * @author  zhangheng
     */
    public function supply_info($params)
    {
        $spu = $params['spu'] ?? "";
        if(empty($spu)) {
            return [];
        }
        $supply_info = Db::name('supply_info')
            ->field('b.id,b.supply_name')
            ->alias('a')
            ->join('qu_supply b','b.id = a.supply_id', 'left')
            ->where('a.spu', $spu)
            ->order('a.created_time desc')
            ->find();
        return $supply_info;
    }



    /**
     * @desc   获取子集sku数据
     * @author luckyXiong
     * @date   2024-07-26
     */
    public function getSkuList($params=[]){
        $limit           = getIsset($params,'limit',10);
        $spu             = getIsset($params,'spu');
        $seller_sku      = getIsset($params,'seller_sku');
        $create_time     = getIsset($params,'create_time');
        $inventory_quantity_new  = getIsset($params,'inventory_quantity_new');
        $on_way_quantity         = getIsset($params,'on_way_quantity');
        $not_send_quantity       = getIsset($params,'not_send_quantity');
        $all_inventory_quantity  = getIsset($params,'all_inventory_quantity');
        $lack_inventory_quantity = getIsset($params,'lack_inventory_quantity');
        $where = $order = [];

        if(!$spu){
            return  $this->jsonMessage(201,false,'spu不能为空!',null);
        }

        if($seller_sku){
            $where[]  = ['seller_sku','=',$seller_sku];
        }


        if ($create_time) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        $where[]  = ['spu','=',$spu];


        if($inventory_quantity_new){
            $order['inventory_quantity_new'] = $inventory_quantity_new;
        }

        if($on_way_quantity){
            $order['on_way_quantity'] = $on_way_quantity;
        }

        if($not_send_quantity){
            $order['not_send_quantity'] = $not_send_quantity;
        }

        if($all_inventory_quantity){
            $order['all_inventory_quantity'] = $all_inventory_quantity;
        }

        if($lack_inventory_quantity){
            $order['lack_inventory_quantity'] = $lack_inventory_quantity;
        }

        if(!$inventory_quantity_new && !$on_way_quantity && !$not_send_quantity && !$all_inventory_quantity && !$lack_inventory_quantity){
            $order['not_send_quantity']       = 'desc';
        }



        $res   = Db::name('product_inventory')
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $list = $res->items()?:[];

        //获取三个库存的总计
        $total_info = Db::name('product_inventory')->where($where)
            ->field('id,inventory_quantity,on_way_quantity,inventory_quantity_new,all_inventory_quantity,not_send_quantity')
            ->select()->toArray();
        $total_inventory_quantity     = array_sum(array_column($total_info, 'inventory_quantity_new'));
        $total_on_way_quantity        = array_sum(array_column($total_info, 'on_way_quantity'));
        $total_not_send_quantity      = array_sum(array_column($total_info, 'not_send_quantity'));
        $total_all_inventory_quantity = array_sum(array_column($total_info, 'all_inventory_quantity'));

        $data = [
            'list'                         => $list,
            'total'                        => $res->total(),
            'total_inventory_quantity'     => $total_inventory_quantity,
            'total_on_way_quantity'        => $total_on_way_quantity,
            'total_not_send_quantity'      => $total_not_send_quantity,
            'total_all_inventory_quantity' => $total_all_inventory_quantity,
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc   导入产品库存
     * @author luckyXiong
     * @date   2024-07-21
     */
    public function import_inventor($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_INVENTORY_PAGE,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }

    }



    /**
     * @desc   导出产品库存
     * @author luckyXiong
     * @date   2024-07-22
     */
    public function exportInventory($params=[]){
        $spu             = getIsset($params,'spu');
        $seller_sku      = getIsset($params,'seller_sku');
        $create_time     = getIsset($params,'created_time');
        $where = [];

        if($spu){
            $where[] = ['spu', 'like', '%' . $spu . '%'];
        }

        if($seller_sku){
            $where[] = ['seller_sku', 'like', '%' . $seller_sku . '%'];
        }


        if ($create_time) {
            $where[]  = ['created_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        $order = ['create_time DESC, update_time DESC'];
        $list   = Db::name('product_inventory')
            ->where($where)
            ->order($order)
            ->select();
        $list = objectToArray($list);

        $header[] = ['spu', 'spu'];
        $header[] = ['商品sku', 'seller_sku'];
        $header[] = ['产品名称', 'product_name'];
        $header[] = ['产品图片', 'product_images'];
        $header[] = ['订单未发数量', 'not_send_quantity'];
        $header[] = ['总库存量', 'all_inventory_quantity'];
        $header[] = ['在途数量', 'on_way_quantity'];
        $header[] = ['仓库缺货数量', 'lack_inventory_quantity'];
        $header[] = ['仓库可用库存', 'inventory_quantity_new'];
        $header[] = ['创建时间', 'create_time'];
        $fileName = "productList_inventory";
        Excel::exportData($list, $header, $fileName, 'xlsx');
        return  $this->jsonMessage(200,true,'导出成功',null);
    }



  



    /**
     * @desc 将导入数据写入目标表
     * @author xx
     * @date 2024-03-21
     */
    public function import_inventory_detail($params=[]){
        $key        = 'import_inventory_detail:'.time();
        $redis_lock = new RedissLock();
        $lock       = $redis_lock::lock($key, $redis_lock::UNBLOCK, 60);
        $seller_sku               = getIsset($params,'seller_sku');
        $SKU                      = getIsset($params,'SKU');
        $product_images           = getIsset($params,'product_images');
        $product_name             = getIsset($params,'product_name');
        $inventory_quantity       = getIsset($params,'inventory_quantity');
        $on_way_quantity          = getIsset($params,'on_way_quantity');
        $not_send_quantity        = getIsset($params,'not_send_quantity');
        $warehouse                = getIsset($params,'warehouse');
        $all_inventory_quantity   = getIsset($params,'all_inventory_quantity');
        $seller_sku_arr           = explode('-',$seller_sku);
        $spu                      = $seller_sku_arr[0]??'';

        $minSku  = '';
        if ($SKU) {
            $SKU = trim($SKU);
            $SKU = array_filter(explode("\n", $SKU), 'trim');
            $minSku = min($SKU);
        }

        if(!$inventory_quantity){
            $inventory_quantity =0;
        }

        if(!$not_send_quantity){
            $not_send_quantity = 0;
        }

        if(!$all_inventory_quantity){
            $all_inventory_quantity = 0;
        }

        if(!$on_way_quantity){
            $on_way_quantity = 0;
        }

        //仓库可用库存
        $inventory_quantity_new  = $all_inventory_quantity - $not_send_quantity;

        //仓库缺货件数
        $lack_inventory_quantity = $not_send_quantity - $all_inventory_quantity;

        if($lack_inventory_quantity<=0){
            $lack_inventory_quantity = 0;
        }

        $product_images_length  = strlen($product_images);

        if($product_images_length>250){
            $product_images = '';
        }

        if($minSku){
            $seller_sku = trim($minSku);
        }


        $temp = [
            'seller_sku'             =>$seller_sku,
            'spu'                    =>$spu,
            'product_name'           =>$product_name,
            'inventory_quantity'     =>$inventory_quantity,
            'on_way_quantity'        =>$on_way_quantity,
            'not_send_quantity'      =>$not_send_quantity,
            'all_inventory_quantity' =>$all_inventory_quantity,
            'inventory_quantity_new' =>$inventory_quantity_new,
            'lack_inventory_quantity'=>$lack_inventory_quantity,
            'product_images'         =>$product_images,
            'warehouse'              =>$warehouse,
            'create_time'            =>date("Y-m-d H:i:s", time()),
            'update_time'            =>date("Y-m-d H:i:s", time()),
        ];

        //查看数据是否存在;
        $exist_info = Db::name('product_inventory')->where('seller_sku',$seller_sku)->find();
        if($exist_info){
            Db::name('product_inventory')->where('id',$exist_info['id'])->update(
                [
                    'product_name'           =>$product_name,
                    'inventory_quantity'     =>$inventory_quantity,
                    'on_way_quantity'        =>$on_way_quantity,
                    'not_send_quantity'      =>$not_send_quantity,
                    'all_inventory_quantity' =>$all_inventory_quantity,
                    'inventory_quantity_new' =>$inventory_quantity_new,
                    'lack_inventory_quantity'=>$lack_inventory_quantity,
                    'update_time'            =>date("Y-m-d H:i:s", time()),
                ]
            );
        }else{
            Db::name('product_inventory')->insert($temp);
        }
        $lock->unlock();
        $info['status'] = 1;
        return  $info;
    }


    /**
     * @param $row
     * @return string[]
     * @desc 数据title 导入组装数据结构
     */
    public function get_excel_row_data($row){
        return [
            'seller_sku'             => empty($row['A'])? '': trim($row['A']),
            'product_images'         => empty($row['R'])? '': trim($row['R']),
            'product_name'           => empty($row['Q'])? '': trim($row['Q']),
            'on_way_quantity'        => empty($row['I'])? '': trim($row['I']),
            'inventory_quantity'     => empty($row['N'])? '': trim($row['N']),
            'not_send_quantity'      => empty($row['L'])? '': trim($row['L']),
            'warehouse'              => empty($row['B'])? '': trim($row['B']),
            'all_inventory_quantity' => empty($row['D'])? '': trim($row['D']),
            'SKU'                    => empty($row['O'])? '': trim($row['O']),
        ];
    }


    /**
     * @desc   库存管理编辑接口
     * @author xx
     * @date 2024-07-25
     */
    public function edit_inventory($params=[]){
           $id                      = $params['id']??'';
           $spu                     = $params['spu']??'';
           $product_name            = $params['product_name']??'';
           $inventory_quantity      = $params['inventory_quantity']??'';
           $on_way_quantity         = $params['on_way_quantity']??'';
           $not_send_quantity       = $params['not_send_quantity']??'';
           $all_inventory_quantity  = $params['all_inventory_quantity']??'';
           $remark                  = $params['remark']??'';
           if(!$id){
               return  $this->jsonMessage(201, false, 'ID不能为空!',null);
           }



           Db::name('product_spu_inventory')->where('id',$id)->update(
                  [
                      'spu'                   =>$spu,
                      'product_name'          =>$product_name,
                      'inventory_quantity'    =>$inventory_quantity,
                      'on_way_quantity'       =>$on_way_quantity,
                      'not_send_quantity'     =>$not_send_quantity,
                      'all_inventory_quantity'=>$all_inventory_quantity,
                      'remark'                =>$remark,
                  ]
           );
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    

    /**
     * @desc   获取产品库存列表
     * @author luckyXiong
     * @date   2024-07-21
     */
    public function export($params=[]){
        $limit                   = getIsset($params,'limit',10);
        $spu                     = getIsset($params,'spu');
        $update_time             = getIsset($params,'update_time');
        $inventory_quantity      = getIsset($params,'inventory_quantity');
        $on_way_quantity         = getIsset($params,'on_way_quantity');
        $not_send_quantity       = getIsset($params,'not_send_quantity');
        $all_inventory_quantity  = getIsset($params,'all_inventory_quantity');
        $purchase_number_num     = getIsset($params,'purchase_number_num');
        $lack_inventory_quantity     = getIsset($params,'lack_inventory_quantity');

        $where = [];
        $order = [];
        if($spu){
            // $where[] = ['spu', '=', $spu];
            $where[] = ['spu', 'like', '%'.$spu.'%'];
        }

        if ($update_time) {
            $where[]  = ['update_time', '>=', date('Y-m-d H:i:s',strtotime($update_time[0]))];
            $where[]  = ['update_time', '<=', date('Y-m-d H:i:s',strtotime($update_time[1]) + 3600*24-1)];
        }


        if($inventory_quantity){
            $order['inventory_quantity_new'] = $inventory_quantity;
        }

        if($on_way_quantity){
            $order['on_way_quantity'] = $on_way_quantity;
        }

        if($not_send_quantity){
            $order['not_send_quantity'] = $not_send_quantity;
        }

        if($all_inventory_quantity){
            $order['all_inventory_quantity'] = $all_inventory_quantity;
        }
        if($lack_inventory_quantity){
            $order['lack_inventory_quantity'] = $lack_inventory_quantity;
        }

        if($purchase_number_num){
            $order['purchase_number_num'] = $purchase_number_num;
        }
        if(empty($order)){
            $order['all_inventory_quantity'] = 'desc';
        }


        $list   = Db::name('product_inventory')
            ->field('
            spu,update_time,
            sum(not_send_quantity) as not_send_quantity,
            sum(all_inventory_quantity) as all_inventory_quantity,
            sum(on_way_quantity) as on_way_quantity,
            sum(lack_inventory_quantity) as lack_inventory_quantity,
            sum(inventory_quantity_new) as inventory_quantity
            ')
            ->where($where)
            ->where('spu',"<>","")
            // ->where('all_inventory_quantity',">",0)
            ->where('update_time',">",date("Y-m-d H:i:s",strtotime("-1 month")))
            ->group('spu')
            ->order($order)
            ->select()->toarray();
            

        $header[] = ['SPU', 'spu'];
        $header[] = ['订单未发件数', 'not_send_quantity'];
        $header[] = ['总库存量', 'all_inventory_quantity'];
        $header[] = ['在途数量', 'on_way_quantity'];
        $header[] = ['仓库缺货件数', 'lack_inventory_quantity'];
        $header[] = ['仓库可用库存', 'inventory_quantity'];
        $header[] = ['最后更新时间', 'update_time'];
        $fileName = "AvailableStock";
        Excel::exportData($list, $header, $fileName, 'xlsx');
        return  $this->jsonMessage(200,true,'导出成功',null);
    }





    /**
     * @desc   可用库存明细
     * @author zhangheng
     * @date   2025-06-17
     */
    public function StockInfo($params=[]){
        $spu = $params['spu'] ?? '';
        $where = [];
        $where[] = ['spu', '=', $spu];
        // $where[] = ['inventory_quantity_new', '>', 0];
        $where[] = ['update_time',">",date("Y-m-d H:i:s",strtotime("-1 month"))];
        $lists = Db::name('product_inventory')
            ->field('seller_sku as sku,sum(inventory_quantity_new) as count')
            ->where($where)
            ->group('seller_sku')
            ->order('sku asc')
            ->select()->toarray();

        $colorCounts = [];
        $sizeCounts = [];
        $Counts_Total = 0;
        
        $sizeOrder = ["XS", "S", "m" ,"M", "L", "XL", "2XL",'2XL/3XL','3xl', "3XL", "4XL", "5XL", "6XL", "7XL"];
        $insize = 0;

        foreach ($lists as $item) { 
            if(empty($item['sku'])){
                continue;
            }
            list($spu,$color, $size) = explode('-', $item['sku'], 3);  

            //统一小写
            $spu = strtolower($spu);
            $sku = $spu."-".$color."-".$size;
            $new_list[$sku] = (int)$item['count'];

            $spu = trim($spu);
            $color = trim($color);
            $size = trim($size);

            if (in_array($size, $sizeOrder)) {  
                $insize = 1;
            }

            if (!isset($colorCounts[$color])) {  
                $colorCounts[$color] = (int)$item['count'];  
            }else{
                $colorCounts[$color] = $colorCounts[$color] + (int)$item['count'];
            }
            //尺码  
            if (!isset($sizeCounts[$size])) {  
                $sizeCounts[$size] = (int)$item['count'];  
            }else{
                $sizeCounts[$size] = $sizeCounts[$size] + (int)$item['count']; 
            }
            $Counts_Total += (int)$item['count']; 
        }
        //排序
        ksort($sizeCounts);
        // 使用自定义排序
        if($insize == 1){
            uksort($sizeCounts, function ($a, $b) use ($sizeOrder) {
                $posA = array_search($a, $sizeOrder);
                $posB = array_search($b, $sizeOrder);
                return $posA - $posB;
            });
        }
        // halt($sizeCounts);
        
        $new_arrs = [];
        foreach ($colorCounts as $k=>$v) {
            $new_arr = [];
            $total = 0;
            foreach ($sizeCounts as $ks=>$vs) {
                $spu = strtolower($spu);
                $name = $spu."-".$k."-".$ks;
                $count = $new_list[$name] ?? 0;
                $new_arr[$ks] = (int)$count;
                $total += (int)$count;
            }
            $new_arr['name'] = $k;
            $new_arr['total'] = $total;
            $new_arrs[] = $new_arr;
        }
        
        $colors = [];
        if(!empty($colorCounts)){
            foreach ($colorCounts as $k=>$v) {
                $Proportion = number_format((float)$v / (float)$Counts_Total*100, 2, '.', '')."%";
                $colors[] = [
                    'name' => $k.":".$v."(".$Proportion.")",  
                    'count' => $v  
                ];  
            }
        }

        $cups = [];
        if(!empty($sizeCounts)){
            foreach ($sizeCounts as $k=>$v) {
                $Proportion = number_format((float)$v / (float)$Counts_Total*100, 2, '.', '')."%";
                $cups[] = [
                    'name' => $k.":".$v."(".$Proportion.")",  
                    'count' => $v  
                ];
            }
        }

        //表头
        $header = [];
        foreach ($sizeCounts as $k=>$v) {
            $header[] = [
                'label' => $k,
                'prop' => $k
            ];
        }


        $data = [
            'list' => $new_arrs,
            'color' => $colors,
            'cup' => $cups,
            'labels' => "SPU: ".$spu,
            'customSizes' => $header,
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }

    

    

    /**
     * @desc   可用库存明细导出
     * @author zhangheng
     * @date   2025-06-17
     */
    public function exportStockInfo($params=[]){
        $spu = $params['spu'] ?? '';
        $where = [];
        $where[] = ['spu', '=', $spu];
        // $where[] = ['inventory_quantity_new', '>', 0];
        $where[] = ['update_time',">",date("Y-m-d H:i:s",strtotime("-1 month"))];
        $lists = Db::name('product_inventory')
            ->field('seller_sku as sku,sum(inventory_quantity_new) as count')
            ->where($where)
            ->group('seller_sku')
            ->order('sku asc')
            ->select()->toarray();

        $colorCounts = [];
        $sizeCounts = [];
        $Counts_Total = 0;

        $sizeOrder = ["XS", "S", "m" ,"M", "L", "XL", "2XL",'2XL/3XL','3xl', "3XL", "4XL", "5XL", "6XL", "7XL"];
        $insize = 0;

        foreach ($lists as $item) { 
            if(empty($item['sku'])){
                continue;
            }
            list($spu,$color, $size) = explode('-', $item['sku'], 3);  

             //统一小写
            $spu = strtolower($spu);
            $sku = $spu."-".$color."-".$size;
            $new_list[$sku] = (int)$item['count'];

            $color = trim($color);
            $size = trim($size);

            if (in_array($size, $sizeOrder)) {  
                $insize = 1;
            }

            if (!isset($colorCounts[$color])) {  
                $colorCounts[$color] = (int)$item['count'];  
            }else{
                $colorCounts[$color] = $colorCounts[$color] + (int)$item['count'];
            }
            //尺码  
            if (!isset($sizeCounts[$size])) {  
                $sizeCounts[$size] = (int)$item['count'];  
            }else{
                $sizeCounts[$size] = $sizeCounts[$size] + (int)$item['count']; 
            }
            $Counts_Total += (int)$item['count']; 
        }
        //排序
        ksort($sizeCounts);
        $sizeOrder = ["XS", "S", "m" ,"M", "L", "XL", "2XL",'2XL/3XL','3xl', "3XL", "4XL", "5XL", "6XL", "7XL"];
        // 使用自定义排序
        if($insize == 1){
            uksort($sizeCounts, function ($a, $b) use ($sizeOrder) {
                $posA = array_search($a, $sizeOrder);
                $posB = array_search($b, $sizeOrder);
                return $posA - $posB;
            });
        }
        // halt($sizeCounts);
        
        $new_arrs = [];
        foreach ($colorCounts as $k=>$v) {
            $new_arr = [];
            $total = 0;
            foreach ($sizeCounts as $ks=>$vs) {
                $spu = trim($spu);
                $name = $spu."-".$k."-".$ks;
                $count = $new_list[$name] ?? 0;
                $new_arr[$ks] = (int)$count;
                $total += (int)$count;
            }
            $new_arr['name'] = $k;
            $new_arr['total'] = $total;
            $new_arrs[] = $new_arr;
        }

        //表头
        $header = [];
        $header[] = ['颜色', 'name'];
        $header[] = ['小计', 'total'];
        foreach ($sizeCounts as $k=>$v) {
            $header[] = [$k,$k];
        }

        $fileName = "SPU-".$spu;
        Excel::exportData($new_arrs, $header, $fileName, 'xlsx');
        return  $this->jsonMessage(200,true,'导出成功',null);
    }


    

    /**
     * @desc   可用库存
     * @author zhangheng
     * @date   2025-06-17
     */
    public function queryStock($params=[]){
        $limit                   = getIsset($params,'limit',10);
        $spu                     = getIsset($params,'spu');
        $update_time             = getIsset($params,'update_time');
        $inventory_quantity      = getIsset($params,'inventory_quantity');
        $on_way_quantity         = getIsset($params,'on_way_quantity');
        $not_send_quantity       = getIsset($params,'not_send_quantity');
        $all_inventory_quantity  = getIsset($params,'all_inventory_quantity');
        $purchase_number_num     = getIsset($params,'purchase_number_num');
        $lack_inventory_quantity = getIsset($params,'lack_inventory_quantity');

        $where = [];
        $order = [];
        if($spu){
            $where[] = ['spu', 'like', '%'.$spu.'%'];
        }

        if ($update_time) {
            if(is_array($update_time)){
                $where[]  = ['update_time', '>=', date('Y-m-d H:i:s',strtotime($update_time[0]))];
                $where[]  = ['update_time', '<=', date('Y-m-d H:i:s',strtotime($update_time[1]) + 3600*24-1)];
            }else{
                $order['update_time'] = $update_time;
            }
        }


        if($inventory_quantity){
            $order['inventory_quantity_new'] = $inventory_quantity;
        }

        if($on_way_quantity){
            $order['on_way_quantity'] = $on_way_quantity;
        }

        if($not_send_quantity){
            $order['not_send_quantity'] = $not_send_quantity;
        }

        if($all_inventory_quantity){
            $order['all_inventory_quantity'] = $all_inventory_quantity;
        }
        if($lack_inventory_quantity){
            $order['lack_inventory_quantity'] = $lack_inventory_quantity;
        }

        if($purchase_number_num){
            $order['purchase_number_num'] = $purchase_number_num;
        }
        if(empty($order)){
            $order['all_inventory_quantity'] = 'desc';
        }

        //最后更新时间
        $update_time = Db::name('product_inventory')
            ->field('update_time')
            ->where($where)
            ->where('spu',"<>","")
            ->order('update_time desc')
            ->find();
        $update_time = $update_time['update_time'] ?? "";
        

        $res   = Db::name('product_inventory')
            ->field('
            spu,update_time,
            sum(not_send_quantity) as not_send_quantity,
            sum(all_inventory_quantity) as all_inventory_quantity,
            sum(on_way_quantity) as on_way_quantity,
            sum(lack_inventory_quantity) as lack_inventory_quantity,
            sum(inventory_quantity_new) as inventory_quantity
            ')
            ->where($where)
            ->where('spu',"<>","")
            ->where('update_time',">",date("Y-m-d H:i:s",strtotime("-1 month")))
            ->group('spu')
            ->order($order)
            ->paginate($limit);
        $list = $res->items()?:[];
        

        $data = [
            'update_time'                  => $update_time,
            'list'                         => $list,
            'total'                        => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }



}